<template>
  <div>
    <!-- title -->
    <PageTitle>
      {{ $t("modules.report.statement") }}
    </PageTitle>
    <el-card
      shadow="never"
      :body-style="{ padding: '0px' }"
      :current-page="pageNo"
      :page-size="pageSize"
      :total="totalCount"
      @current-change="handleCurrentChange"
    >
      <el-form class="p-4" inline :model="dataForm">
        <el-form-item>
          <el-input
            ref="name"
            v-model="userName"
            clearable
            class="inputModify"
            :placeholder="$t('common.customer_name')"
            @clear="clearUserName"
            @focus="openCustomerList"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="selectTime"
            type="monthrange"
            unlink-panels
            format="YYYY-MM"
            value-format="YYYYMM"
            range-separator="-"
            :start-placeholder="$t('common.start_time')"
            :end-placeholder="$t('common.end_time')"
            :picker-options="pickerOptions"
        /></el-form-item>
        <el-form-item>
          <el-button
            v-permission="{ permission: ['10401002.MANAGE', '10401002.QUERY'] }"
            type="primary"
            class="w-8"
            @click="getStatementList"
          >
            <svg-icon icon-class="search" class="text-lg" />
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-tooltip
            class="item"
            effect="dark"
            :content="$t('flycare.statement.generate_title')"
            placement="top"
          >
            <el-button
              v-permission="{ permission: '10401002.MANAGE' }"
              type="primary"
              class="w-8"
              @click="openGenerateStatement"
            >
              <svg-icon icon-class="gen-statement" />
            </el-button>
            <!-- <el-button type="primary" size="small" icon="el-icon-files"   @click="generateReport"></el-button> -->
          </el-tooltip></el-form-item
        >
      </el-form>
      <el-table v-loading="loading" :data="reportList" stripe>
        <el-table-column prop="statisticMonth" :label="$t('common.month')" />
        <el-table-column :label="$t('common.customer_name')" prop="userName">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span
                      >{{ $t("common.customer_type") }}:
                      {{ scope.row.characterCode }} (ID: {{ scope.row.keyId }})</span
                    ><br />
                  </div>
                </template>
                <div>
                  {{ scope.row.userName }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" :label="$t('modules.invoice.amount')">
          <template v-slot="scope">
            {{ scope.row.totalAmount.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column
          prop="signEntityId"
          :label="$t('modules.contract.sign_entity_id')"
        >
          <template v-slot="scope">
            {{ getSignEntityName(scope.row.signEntityId) }}
          </template>
        </el-table-column>
        <!--            <el-table-column :label="$t('modules.report.notify_oa_time')" prop="noticeOaTime">-->
        <!--              <template v-slot="scope">-->
        <!--                <div>-->
        <!--                  <el-tooltip placement="top-start">-->
        <!--                    <div slot="content" style="max-width:300px;line-height:160%;">-->
        <!--                      <span>{{ scope.row.noticeOaTime }}</span><br>-->
        <!--                    </div>-->
        <!--                    <div>-->
        <!--                      {{ scope.row.noticeOaDate }}-->
        <!--                    </div>-->
        <!--                  </el-tooltip>-->
        <!--                </div>-->
        <!--              </template>-->
        <!--            </el-table-column>-->
        <el-table-column prop="creTime" :label="$t('common.create_time')">
          <template v-slot="scope">
            <div>
              <el-tooltip placement="top-start">
                <template #content>
                  <div style="max-width: 300px; line-height: 160%">
                    <span>{{ scope.row.creTime }}</span
                    ><br />
                  </div>
                </template>
                <div>
                  {{ scope.row.creDate }}
                </div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="75px">
          <template v-slot="scope">
            <el-button
              class="w-8"
              text
              @click="
                () =>
                  $router.push({
                    path: '/service-management/statement/detail',
                    query: { piDetail: JSON.stringify(scope.row) },
                  })
              "
            >
              <svg-icon icon-class="View" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <gen-statement
      ref="genStatement"
      v-model="genStatementVisible"
      @openGenStatementResult="openGenStatementResult"
      @refreshData="getStatementList"
    />
    <gen-statement-result ref="genStatementFailed" v-model="genStatementFailedVisible" />
    <customer-list
      ref="customerList"
      v-model="customerListVisible"
      @confirmSelect="confirmSelectCustomer"
    />
  </div>
</template>

<script>
import { getPIs } from "@/api/statement";
import { toTime, toTenYMD } from "@/utils/index";
import GenStatement from "@/views/service-management/statement/components/gen-statement";
import GenStatementResult from "@/views/service-management/statement/components/gen-statement-result";
import CustomerList from "@/views/service-management/components/customer-list";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  name: "ServiceManagementStatement",
  components: {
    GenStatement,
    GenStatementResult,
    CustomerList,
    PageTitle,
  },
  data() {
    return {
      settings: {
        conditions: [],
        columns: [],
      },
      loading: false,
      genStatementFailedVisible: false,
      genStatementVisible: false,
      customerListVisible: false,
      totalCount: undefined,
      pageNo: 1,
      pageSize: 10,
      userName: "",
      userData: {
        characterCode: "",
        keyId: "",
      },
      customerData: [],
      radio: "",
      status: "",
      reportList: [],
      reportForm: {
        reportId: "",
        confirmState: "",
      },
      signOptions: [
        { label: "新大陆支付NLPM01", value: "NLPM01" },
        { label: "新大陆香港NLHK01", value: "NLHK01" },
      ],
      reportStatus: "reject",
      selectTime: [],
      pickerOptions: {
        shortcuts: [
          {
            text: this.$t("common.last_month"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1);
              end.setMonth(end.getMonth() - 1);
              picker.$emit("pick", [start, end]);
            },
          },
          // {
          //   text: this.$t('common.current_month'),
          //   onClick(picker) {
          //     picker.$emit('pick', [new Date(), new Date()])
          //   }
          // },
          {
            text: this.$t("common.half_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: this.$t("common.one_year"),
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 12);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  computed: {
    settingList() {
      return {
        columns: [
          {
            title: this.$t("common.short_name"),
            code: "SHORT_NAME",
          },
          {
            title: this.$t("common.address"),
            code: "ADDRESS",
          },
          {
            title: this.$t("common.link_man"),
            code: "LINKMAN",
          },
          {
            title: this.$t("common.mobile"),
            code: "MOBILE",
          },
          {
            title: this.$t("common.email"),
            code: "EMAIL",
          },
        ],
      };
    },
    defaultSettings() {
      return {
        columns: [],
      };
    },
  },
  mounted() {
    this.$store.commit("app/ADD_KEEP_ALIVE_LIST", "ServiceManagementStatement");
    this.getStatementList();
  },
  beforeRouteLeave(to, from, next) {
    console.log(to);
    if (to.name !== "detailStatement") {
      this.$store.commit("app/REMOVE_KEEP_ALIVE_LIST", "ServiceManagementStatement");
    }
    next();
  },
  activated() {
    this.getStatementList();
  },
  methods: {
    showHeader(label) {
      var list = this.settings["columns"];
      return list ? list.includes(label) : false;
    },
    showFormItem(label) {
      var list = this.settings["conditions"];
      return list ? list.includes(label) : false;
    },
    openGenerateStatement() {
      this.genStatementVisible = true;
      this.$nextTick(() => {
        this.$refs.genStatement.openDialog();
      });
    },
    openGenStatementResult(genStatementResult) {
      this.genStatementFailedVisible = true;
      this.$nextTick(() => {
        this.$refs.genStatementFailed.openDialog(genStatementResult);
      });
    },
    openCustomerList() {
      this.customerListVisible = true;
      this.$nextTick(() => {
        this.$refs.customerList.openDialog();
      });
    },
    getSignEntityName(signEntityId) {
      if (signEntityId) {
        const signEntity = this.signOptions.filter((item) => item.value === signEntityId);
        if (signEntity) {
          return signEntity[0].label;
        } else {
          return signEntityId;
        }
      }
      return "";
    },
    confirmSelectCustomer(selectedCustomer) {
      this.userData.characterCode = selectedCustomer.characterCode;
      this.userData.keyId = selectedCustomer.keyId;
      this.userName = selectedCustomer.name;
      // console.log(selectedCustomer)
    },
    // 获取对账单列表
    getStatementList() {
      this.loading = true;
      let start, end;
      if (this.selectTime === null) {
        start = end = "";
      } else if (this.selectTime.length === 0) {
        start = end = "";
      } else {
        start = this.selectTime[0].toString();
        end = this.selectTime[1].toString();
      }
      const params = {
        characterCode: this.userData.characterCode,
        keyId: this.userData.keyId,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
        effectiveDate: start,
        expiringDate: end,
      };
      getPIs(params)
        .then((res) => {
          this.totalCount = res.total;
          this.reportList = res.list;
          for (let i = 0; i < this.reportList.length; i++) {
            if (this.reportList[i].noticeOaTime != null) {
              this.reportList[i].noticeOaDate = toTenYMD(this.reportList[i].noticeOaTime);
              this.reportList[i].noticeOaTime = toTime(this.reportList[i].noticeOaTime);
            }
            if (this.reportList[i].creTime) {
              this.reportList[i].creDate = toTenYMD(this.reportList[i].creTime);
              this.reportList[i].creTime = toTime(this.reportList[i].creTime);
            }
          }
          this.loading = false;
        })
        .catch((err) => {
          this.$message.error(err.message);
          this.loading = false;
        });
    },
    // 处理分页
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getStatementList();
    },
    // 清空Customer Name
    clearUserName() {
      this.userData.characterCode = "";
      this.userData.keyId = "";
    },
  },
};
</script>

<style scoped>
.title-logo {
  font-size: 0.8em;
  margin-left: 0px;
  color: #909399;
}
.box-header {
  font-weight: bold;
  font-size: 1.8em;
  color: #12263f;
}
.textLayout {
  display: flex;
  justify-content: center;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 12px;
}

.operateIcon {
  display: inline-block;
  width: 40px;
  color: #2c7be5;
}
.operateIcon :hover {
  color: #484ff3;
  cursor: pointer;
}
</style>
